<template>
    <div class="category-detail-page">
        <el-card shadow="never">
            <el-form
                :model="form"
                label-position="right"
                label-suffix=":"
                label-width="150px"
                ref="form"
                :rules="rules">
                <el-form-item label="企业名称" prop="name">
                    <el-input
                        v-model="form.name"
                        placeholder="请输入企业名称"
                        class="input-width"
                    ></el-input>
                </el-form-item>
                <el-form-item label="企业账号" prop="account">
                    <el-input
                        v-model="form.account"
                        placeholder="请输入企业账号"
                        class="input-width"
                    ></el-input>
                </el-form-item>
                <el-form-item label="后台管理角色权限" prop="role_id">
                    <el-select
                        v-model="form.role_id"
                        clearable>
                        <el-option
                            v-for="item in companyPermissionOptions"
                            :key="item.id"
                            :label="item.name"
                            :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="企业所在城市">
                    <el-input
                        v-model="form.city"
                        placeholder="请输入企业所在城市"
                        class="input-width"
                    ></el-input>
                </el-form-item>
                <el-form-item label="企业规模人数">
                    <el-input-number
                        v-model="form.member_amount"
                        :min="1"
                        class="input-width"
                    ></el-input-number>
                </el-form-item>
                <el-form-item label="企业所属行业">
                    <el-select
                        v-model="form.industry_id"
                        clearable>
                        <el-option
                            v-for="item in industryOptions"
                            :key="item.id"
                            :label="item.name"
                            :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="企业简介">
                    <el-input
                        v-model="form.introduction"
                        type="textarea"
                    ></el-input>
                </el-form-item>
                <el-form-item label="联系人姓名">
                    <el-input
                        v-model="form.contact_name"
                        placeholder="请输入企业联系人姓名"
                        class="input-width"
                    ></el-input>
                </el-form-item>
                <el-form-item label="联系方式">
                    <el-input
                        v-model="form.contact"
                        placeholder="请输入企业联系方式"
                        class="input-width"
                    ></el-input>
                </el-form-item>
                <el-form-item label="msup备注信息">
                    <el-input
                        v-model="form.note"
                        type="textarea"
                    ></el-input>
                </el-form-item>
                <el-form-item label="企业账号状态">
                    <el-select v-model="form.admin_account_status">
                        <el-option label="短期使用" :value="1"/>
                        <el-option label="首次付费" :value="2"/>
                        <el-option label="续约付费" :value="3"/>
                        <el-option label="长期赠送" :value="4"/>
                        <el-option label="测试赠送" :value="5"/>
                    </el-select>
                </el-form-item>
                <el-form-item label="客户或账号维护日志">
                    <Tinymce v-model="companyLog.comment"/>
                    <div class="my-4 text-center">
                        <el-button
                            :disabled="!companyLog.comment"
                            :loading="loading"
                            type="primary"
                            @click="onAddlog">添加</el-button>
                    </div>

                    <div class="log">
                        <div class="item mb-4" v-for="(item, i) in logList" :key="i">
                            <div class="title">
                                {{ item.created_at | formatTime }} {{ item.admin_account }}
                            </div>
                            <div class="content">
                                <div
                                    :class="`content-in ${item.show ? 'active' : ''}`"
                                    v-html="item.comment"></div>
                                <el-button class="btn" type="text" @click="onShowLine(item.id, item.admin_account)">
                                    详情<i class="el-icon-arrow-right"></i>
                                </el-button>
                            </div>
                        </div>
                    </div>
                    <el-button
                        v-if="logList.length && !logForm.last"
                        :loading="loading"
                        @click="fetchLog(1)">加载更多</el-button>
                </el-form-item>
            </el-form>
            <div class="text-center">
                <el-button :loading="posting" type="primary" @click="onSave">保 存</el-button>
            </div>
        </el-card>
    </div>
</template>

<script>
import Tinymce from '@/components/base/Tinymce';

export default {
    components: {
        Tinymce,
    },
    data() {
        return {
            loading: false,
            posting: false,
            form: {
                name: '',
                account: '',
                role_id: '',
                city: '',
                industry_id: '',
                member_amount: '',
                contact_name: '',
                contact: '',
                introduction: '',
                note: '',
                admin_account_status: '',
            },
            id: this.$route.params.id,
            industryOptions: [],
            companyPermissionOptions: [],
            rules: {
                name: [
                    { required: true, message: '企业名称不能为空', trigger: 'blur' },
                ],
                account: [
                    { required: true, message: '企业账号不能为空', trigger: 'blur' },
                ],
                role_id: [
                    { required: true, message: '企业管理角色权限不能为空', trigger: 'blur' },
                ],
            },

            companyLog: {
                company_id: this.$route.params.id,
                comment: '',
            },
            logList: [],
            logForm: {
                companyId: this.$route.params.id,
                page: 1,
                size: 10,
                last: false,
            },
        };
    },
    methods: {
        onSave() {
            this.$refs.form.validate((valid) => {
                if (!valid) return;
                if (!this.form.industry_id) {
                    this.form.industry_id = 0;
                }
                this.posting = true;
                this.form.account = this.form.account.trim();
                if (this.id) {
                    API.put(`company/${this.id}`, this.form).then(() => {
                        this.posting = false;
                        this.$router.push({name: 'CompanyManage'});
                    }).catch(err => {
                        $ele.$message.error(err.message);
                    }).finally(() => this.posting = false);
                } else {
                    API.post('company', this.form).then((res) => {
                        $ele.$confirm(`账号: ${res.account} 密码: ${res.password}`, '新建企业账号成功', {
                            confirmButtonText: '确定',
                            type: 'warning',
                        }).then(() => {
                            this.$router.push({name: 'CompanyManage'});
                        }).catch(() => {
                            this.$router.push({name: 'CompanyManage'});
                        });
                    }).catch(err => {
                        $ele.$message.error(err.message);
                    }).finally(() => this.posting = false);
                }
            });
        },
        fetchData() {
            if (this.id) {
                API.get(`company/${this.id}`).then((res) => {
                    for (const i of Object.keys(this.form)) {
                        if (res[i]) this.form[i] = res[i];
                    }
                });
            }
        },
        fetchIndustryData() {
            API.get('industry/list').then((res) => {
                this.industryOptions = res;
            });
        },
        fetchPermissionData() {
            // 针对企业角色权限
            API.get('role/list', {params: {type: 2}}).then((res) => {
                this.companyPermissionOptions = res;
            });
        },

        onAddlog() {
            if (!this.id) return $ele.$message.warning('请完成企业创号的创建，保存后，再添加账号维护日志。');

            this.loading = true;
            API.post('company/log', this.companyLog).then(() => {
                $ele.$message.success('添加日志成功');
                this.companyLog.comment = '';
                this.fetchLog();
            }).finally(() => this.loading = false);
        },

        fetchLog(reset) {
            const logForm = this.logForm;
            if (!reset) {
                logForm.page = 1;
                this.logList = [];
            } else logForm.page++;

            API.get('company/log/page', {params: logForm}).then((res) => {
                const logList = [...this.logList, ...res.content];

                const regex = /<img[\d\D]*?\/>/g;
                for (const item of logList) {
                    item.comment = item.comment.replace(regex, '[图片]');
                }

                logList.map(item => {
                    item.show = false;
                    return item;
                });

                this.logList = logList;

                this.logForm.last = res.pagination.last === logForm.page;
            });
        },

        onShowLine(id, name) {
            this.$router.push({
                name: 'Company.Log',
                params: {
                    id,
                },
                query: {
                    name,
                },
            });
        },
    },
    mounted() {
        this.fetchIndustryData();
        this.fetchPermissionData();
        this.fetchData();

        if (this.$route.params.id) {
            this.fetchLog();
        }
    },
};
</script>

<style lang="scss">
.category-detail-page {
    .input-width {
        width: 300px;
    }
    .picture {
        width: 200px;
        height: 200px;
        line-height: 200px;
    }
    .uploader-icon {
        font-size: 20px;
        color: #8c939d;
        text-align: center;
    }
    .image-uploader {
        border: 1px dashed #d9d9d9;
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
    }

    .el-input__inner {
        height: 35px;
        line-height: 35px;
    }

    .el-input-number span {
        height: 33px;
        line-height: 33px;
    }

    .text-center .el-button {
        width: 68px;
        height: 33px;
    }

    .log .title {
        color: rgb(189, 189, 189);
    }

    .content-in {
        display: -webkit-box;
        -webkit-line-clamp: 2;
        -webkit-box-orient: vertical;
        overflow: hidden;

        &.active {
            -webkit-line-clamp: 999;
        }
    }
}
</style>
